import router from "./router";
import { useUserStore } from "./store/user";
import { getToken } from "@/utils/cookie";
const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
    const store = useUserStore()

    if (!getToken()) {

        if (whiteList.indexOf(to.path) !== -1) { // 在白名单内的
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }

    } else {
        if (to.path === '/login') {
            next(from.path)
        } else {
            // 判断是否有权限进入该页面
            const children = []
            const parList = []
            const permissionMenu = JSON.parse(localStorage.getItem("permissionMenu"))
            permissionMenu.forEach(item => {
                parList.push(item.path)
                if (item.children) {
                    item.children.forEach(i => {
                        children.push(i.path)
                    })
                }

            })
            const allRouter = router.getRoutes().map(item => item.path)
            if (allRouter.indexOf(to.path) !== -1 ) {
                if (parList.indexOf(to.path) !== -1 || children.indexOf(to.path) !== -1 || to.path === '/403' || to.path ==='/404') {
                    next()
                    return
                } else {
                    next('/403')
                }
            } else {
                next('/404')
            }



            // next()
            // const newRoutes =[...store.permissionMenu]
            // console.log(permissionMenu,router.getRoutes());
            // newRoutes.forEach(r => {
            //     router.addRoute(r)  
            // })
            // console.log(newRoutes);

            // //     next({ ...to, replace: true })
        }

    }

})